<!--
 * @Description: 
 * @Version: V1.0.0
 * @Author: yangshangru yangshangru@supconit.com
 * @Date: 2024-07-31 09:12:10
 * @LastEditors: yangshangru yangshangru@supconit.com
 * @LastEditTime: 2024-08-02 10:21:44
 * @FilePath: RoomReserve.vue
 * 2024-07-31 09:12:10
-->
<template>
  <div class="room-reservations">
    <div class="top-container">
      <div class="form-container">
        <div class="form-item">
          <span style="width: 80px">会议室：</span>
          <n-select
            v-model:value="room"
            clearable
            :options="roomList"
          />
        </div>
        <div class="form-item">
          <span style="width: 6cap">日期：</span>
          <n-date-picker
            v-model:value="dateRange"
            type="daterange"
            clearable
            :is-date-disabled="disablePastDates"
          />
          <!-- <n-date-picker
            v-model:value="meetingDate"
            type="date"
            value-format="yyyy-MM-dd"
          /> -->
        </div>
      </div>
      <div class="form-btns">
        <n-button
          type="primary"
          round
          @click="handleReserve"
          :disabled="!canReserve"
        >
          预定
        </n-button>
        <n-button
          type="primary"
          round
          ghost
          @click="goReserveRecords"
        >
          预定记录
        </n-button>
      </div>
    </div>
    <div class="room-legend">
      <div class="legend-item">
        <div class="legend-item-name">已选择</div>
      </div>
      <div class="legend-item">
        <div class="legend-item-name">我预订</div>
      </div>
      <div class="legend-item">
        <div class="legend-item-name">已预定</div>
      </div>
    </div>
    <div class="room-list">
      <MeetingRoomScheduler
        v-for="item in selectRooms"
        :key="item.value"
        :roomInfo="item.info"
        :days="filteredDays"
        :roomReservations="getRoomReservations(item.value)"
        @selectionMade="handleSelection"
      />
    </div>

    <!-- <div
      v-if="selectedTimeSlot"
      class="selection-info"
    >
      <h2>已选择时间段：</h2>
      <p>开始日期：{{ selectedTimeSlot.startDay }}</p>
      <p>结束日期：{{ selectedTimeSlot.endDay }}</p>
      <p>开始时间：{{ selectedTimeSlot.startTime }}</p>
      <p>结束时间：{{ selectedTimeSlot.endTime }}</p>
    </div> -->
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn' // 导入中文语言包
import { useRouter, useRoute } from 'vue-router'
import MeetingRoomScheduler from './components/MeetingRoomScheduler.vue'
import type { Day, RoomInfo, RoomItem } from '@/types/interfaces'
import { NButton, NSelect, NDatePicker, useMessage } from 'naive-ui'
import { sendRequest } from '@/utils/api'
import { useReservationStore } from '@/stores/reservationStore'

dayjs.locale('zh-cn') // 设置 dayjs 使用中文
const message = useMessage()
const router = useRouter()
const route = useRoute()

const room = ref('')
const roomList = ref<RoomItem[]>([])
const dateRange = ref<[number, number] | null>(null)
const days = ref<Day[]>([])
const reservationStore = useReservationStore()
const reservationsData = ref<any[]>([])

// 获取会议室列表
const fetchRoomList = async () => {
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomList',
    override: {
      params: {
        page: 1,
        limit: 100 // 假设我们想获取所有会议室，可以设置一个较大的限制
      }
    }
  })

  if (error) {
    message.error(error.message || '获取会议室列表失败')
    return
  }

  if (res.code === 0 && res.data && Array.isArray(res.data.list)) {
    roomList.value = res.data.list.map((item: any) => ({
      label: item.name,
      value: item.id.toString(),
      info: {
        id: item.id,
        name: item.name,
        capacity: item.suggestedNumber,
        facilities: item.facility ? item.facility.split(',') : []
      }
    }))
  } else {
    message.error('获取会议室列表失败')
  }
}

const selectRooms = computed<RoomItem[]>(() => {
  if (room.value) {
    const selectedRoom = roomList.value.find((item) => item.value === room.value)
    return selectedRoom ? [selectedRoom] : []
  } else {
    return roomList.value
  }
})

const generateDayData = (date: dayjs.Dayjs): Day => {
  return {
    date: date.format('M月D日'),
    dayOfWeek: `周${date.format('dd')}`,
    fullDate: date.format('YYYY-MM-DD'),
    timeSlots: []
  }
}

const fetchReservationData = async (start: dayjs.Dayjs, end: dayjs.Dayjs) => {
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomReservationInfo',
    override: {
      params: {
        roomId: room.value || undefined
      }
    }
  })

  if (error) {
    message.error(error.message || '获取预约数据失败')
    return
  }

  if (res.code === 0 && Array.isArray(res.data)) {
    reservationsData.value = res.data
    // 生成日期范围
    const daysCount = end.diff(start, 'day') + 1
    days.value = Array.from({ length: daysCount }, (_, index) =>
      generateDayData(start.add(index, 'day'))
    )
  } else {
    message.error('获取预约数据失败')
  }
}

const getRoomReservations = (roomId: string) => {
  const roomData = reservationsData.value.find(
    (room) => room.conferenceRoomId.toString() === roomId
  )
  if (!roomData) return []

  return [
    ...roomData.reservationInfoVoList.map((reservation: any) => ({
      ...reservation,
      type: 'booked'
    })),
    ...roomData.myReservationInfoVoList.map((reservation: any) => ({
      ...reservation,
      type: 'myBooking'
    }))
  ]
}

const loadDefaultData = () => {
  const start = dayjs()
  const end = room.value ? start.add(9, 'day') : start.add(3, 'day')
  fetchReservationData(start, end)
}

// 监听 room 和 dateRange 的变化
watch([room, dateRange], () => {
  if (dateRange.value) {
    const [startDate, endDate] = dateRange.value
    fetchReservationData(dayjs(startDate), dayjs(endDate))
  } else {
    loadDefaultData()
  }
})

// onMounted(async () => {
//   await fetchRoomList()
//   loadDefaultData()
// })

watch(
  () => route,
  async () => {
    if (route.path == '/OA/Meeting/RoomReserve') {
      await fetchRoomList()
      loadDefaultData()
    }
  },
  { deep: true, immediate: true }
)

const disablePastDates = (ts: number) => {
  return ts < Date.now() - 24 * 60 * 60 * 1000
}

const selectedTimeSlot = ref<any>(null)

const handleSelection = (selection: any) => {
  console.log('用户选择了时间范围:', selection)
  selectedTimeSlot.value = selection
}

// const meetingDate = ref(null)

// 修改 filteredDays 计算属性
const filteredDays = computed<Day[]>(() => {
  return days.value
})

const canReserve = computed(() => !!selectedTimeSlot.value)
const handleReserve = () => {
  if (!canReserve.value) {
    message.warning('请选择会议时间')
    return
  }

  // 将预订信息存储到 Pinia store
  reservationStore.setReservationInfo({
    roomId: selectedTimeSlot.value!.roomId,
    roomName: selectedTimeSlot.value!.roomName,
    startTime: selectedTimeSlot.value!.start.toISOString(),
    endTime: selectedTimeSlot.value!.end.toISOString(),
    reservationTime: [
      selectedTimeSlot.value!.start.toISOString(),
      selectedTimeSlot.value!.end.toISOString()
    ],
    facilities: selectedTimeSlot.value!.facilities
  })

  console.log(reservationStore, 2333)

  // 跳转到会议预订提交页面
  router.push({ name: 'OA/Meeting/RoomReserveForm' })
}

const goReserveRecords = () => {
  router.push('/OA/Meeting/RoomReservationsList')
}
</script>

<style scoped lang="scss">
.room-reservations {
  width: 100%;
  background: #fff;
  .top-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 104px;
    padding: 0 60px;
    background: #e1e1e1;

    .form-container {
      display: flex;
      gap: 52px;
      .form-item {
        display: flex;
        align-items: center;
        width: 388px;
        span {
          color: #4e5969;
          font-size: 16px;
        }
      }
    }
    .form-btns {
      display: flex;
      gap: 16px;
    }
  }
  .room-legend {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 32px;
    margin: 14px 0;
    .legend-item {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      width: 140px;
      height: 32px;
      padding-right: 4px;
      border-radius: 59px;
      background: rgba(10, 205, 130, 0.2);
      &::before {
        content: '';
        position: absolute;
        left: 0;
        display: flex;
        width: 32px;
        height: 32px;
        border-radius: 53px;
        background: #00895b;
      }
      &-name {
        display: flex;
        height: 24px;
        padding: 3px 11px;
        justify-content: center;
        align-items: center;
        border-radius: 53px;
        background: #fff;
        box-shadow: 0px 2px 2px 0px rgba(103, 104, 175, 0.2);
        color: #000;
        font-size: 14px;
      }
      &:nth-child(2) {
        background: rgba(38, 125, 240, 0.2);
        &::before {
          background: #267df0;
        }
      }
      &:nth-child(3) {
        background: rgba(134, 144, 156, 0.2);
        &::before {
          background: #86909c;
        }
      }
    }
  }
  .room-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
    margin-bottom: 20px;
  }
}
</style>
